//
//  VersionManager.m
//  SDSY
//
//  Created by 蓝布鲁 on 2018/1/23.
//  Copyright © 2018年 蓝布鲁. All rights reserved.
//

#import "VersionManager.h"
#import "UIAlertController+Simple.h"

@implementation VersionManager
+ (void)checkUpdateWithAppStoreID:(NSString *)appStoreID silent:(BOOL)isSilent{
    [[NetworkTool shareInstance] requireMethodType:GETWITHBASEURLTYPE
                                         URLString:[NSString stringWithFormat:@"https://itunes.apple.com/cn/lookup?id=%@", appStoreID]
                                        parameters:nil
                                           success:^(NSDictionary *respondDictionary) {
                                               NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];

                                               NSString *currentVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];

                                               //KEYresultCount = 1//表示搜到一个符合你要求的APP
                                               //results =（）//这是个只有一个元素的数组，里面都是app信息，那一个元素就是一个字典。里面有各种key。其中有 trackName （名称）trackViewUrl = （下载地址）version （可显示的版本号）等
                                               NSArray *resultsArray = respondDictionary[@"results"];

                                               if (resultsArray.count < 1) {
                                                   NSLog(@"此APPID为未上架的APP或者查询不到");
                                                   if(!isSilent){
                                                       [SVProgressHUD showErrorWithStatus:@"此APPID为未上架的APP或者查询不到 !"];
                                                   }
                                                   return;
                                               }

                                               NSDictionary *appStoreDictionary = [resultsArray firstObject];

                                               NSString *appStoreVersion = appStoreDictionary[@"version"];//App Store版本号
                                               NSString *releaseNotes = [appStoreDictionary objectForKey:@"releaseNotes"];//更新日志
                                               NSString *trackViewUrl = [appStoreDictionary objectForKey:@"trackViewUrl"];

                                               //打印版本号
                                               NSLog(@"当前版本号:%@\n商店版本号:%@", currentVersion, appStoreVersion);
                                               //设置版本号
                                               currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
                                               if (currentVersion.length==2) {
                                                   currentVersion  = [currentVersion stringByAppendingString:@"0"];
                                               }else if (currentVersion.length==1){
                                                   currentVersion  = [currentVersion stringByAppendingString:@"00"];
                                               }
                                               appStoreVersion = [appStoreVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
                                               if (appStoreVersion.length==2) {
                                                   appStoreVersion  = [appStoreVersion stringByAppendingString:@"0"];
                                               }else if (appStoreVersion.length==1){
                                                   appStoreVersion  = [appStoreVersion stringByAppendingString:@"00"];
                                               }

                                               BOOL isNewVersion = [self compareVersionsFormAppStoreVersion:appStoreVersion currentAppVersion:currentVersion];

                                               //App Store有新版本 则更新版本
                                               if(isNewVersion == YES) {

                                                   NSString *message = releaseNotes;

                                                   UIAlertController *updateAlertController = [UIAlertController alertControllerWithTitle:@"应用版本有更新" message:message preferredStyle:UIAlertControllerStyleAlert];

                                                   UIAlertAction *updateAlertAction = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                                                       //此处加入应用在App Store的地址，方便用户去跳转更新，一种实现方式如下
                                                       //NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/id%@?ls=1&mt=8", appStoreID]];
                                                       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:trackViewUrl]];
                                                   }];

                                                   UIAlertAction *cancelAlertAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

                                                   [updateAlertController addAction:updateAlertAction];
                                                   [updateAlertController addAction:cancelAlertAction];
                                                   [updateAlertController showWithCompletion:nil];
                                               }else {
                                                   NSLog(@"您当前版本已经最新");
                                                   if(!isSilent){
                                                       [SVProgressHUD showSuccessWithStatus:@"您当前版本已经最新 !"];
                                                   }
                                               }
                                           } failure:^(NSError *error) {
                                                if(!isSilent){
                                                    [SVProgressHUD showfailed];
                                                }
                                           }];
}

+ (void)checkUpdateWithAppStoreID:(NSString *)appStoreID day:(NSInteger)day {
    NSDate *date = [[NSUserDefaults standardUserDefaults] objectForKey:@"VersionManager.checkDate"];
    NSDate *now = [NSDate date];

    [[NSUserDefaults standardUserDefaults] setObject:now forKey:@"VersionManager.checkDate"];
    if(date == nil){
        [self checkUpdateWithAppStoreID:appStoreID silent:YES];
        return;
    }
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *cmps = [calendar components:NSCalendarUnitDay fromDate:date toDate:now options:0];
    if(cmps.day > day){
        [self checkUpdateWithAppStoreID:appStoreID silent:YES];
    }

}


//比较版本的方法
+ (BOOL)compareVersionsFormAppStoreVersion:(NSString*)AppStoreVersion currentAppVersion:(NSString*)currentAppVersion {

    BOOL littleSunResult = false;

    NSMutableArray* a = (NSMutableArray*) [AppStoreVersion componentsSeparatedByString: @"."];
    NSMutableArray* b = (NSMutableArray*) [currentAppVersion componentsSeparatedByString: @"."];

    while (a.count < b.count) { [a addObject: @"0"]; }
    while (b.count < a.count) { [b addObject: @"0"]; }

    for (int j = 0; j<a.count; j++) {
        if ([[a objectAtIndex:j] integerValue] > [[b objectAtIndex:j] integerValue]) {
            littleSunResult = true;
            break;
        }else if([[a objectAtIndex:j] integerValue] < [[b objectAtIndex:j] integerValue]){
            littleSunResult = false;
            break;
        }else{
            littleSunResult = false;
        }
    }
    return littleSunResult;//true就是有新版本，false就是没有新版本
}

@end
